package com.example.clipboardsyncapp.ui.viewmodel

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.clipboardsyncapp.data.api.ClipboardApi
import com.example.clipboardsyncapp.data.model.ClipboardItem
import com.example.clipboardsyncapp.data.store.UserPreferences
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import org.json.JSONArray

class MainViewModel(
    private val api: ClipboardApi,
    private val context: Context
) : ViewModel() {

    private val userPreferences = UserPreferences(context)
    private val clipboardManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager

    private val _loginState = MutableStateFlow<LoginState>(LoginState.NotLoggedIn)
    val loginState: StateFlow<LoginState> = _loginState.asStateFlow()

    private val _clipboardItems = MutableStateFlow<List<ClipboardItem>>(emptyList())
    val clipboardItems: StateFlow<List<ClipboardItem>> = _clipboardItems.asStateFlow()

    private val _syncState = MutableStateFlow<SyncState>(SyncState.Idle)
    val syncState: StateFlow<SyncState> = _syncState.asStateFlow()

    init {
        checkLoginState()
    }

    private fun checkLoginState() {
        viewModelScope.launch {
            userPreferences.authCookie.collect { cookie ->
                if (!cookie.isNullOrEmpty()) {
                    _loginState.value = LoginState.LoggedIn
                    loadHistory()
                } else {
                    _loginState.value = LoginState.NotLoggedIn
                }
            }
        }
    }

    fun login(password: String, remember: Boolean = false) {
        viewModelScope.launch {
            _loginState.value = LoginState.Loading
            api.login(password, remember)
                .onSuccess {
                    _loginState.value = LoginState.LoggedIn
                    loadHistory()
                }
                .onFailure {
                    _loginState.value = LoginState.Error(it.message ?: "登录失败")
                }
        }
    }

    fun syncClipboard(content: String) {
        viewModelScope.launch {
            _syncState.value = SyncState.Syncing
            api.syncClipboard(content)
                .onSuccess { newItem ->
                    _clipboardItems.value = listOf(newItem) + _clipboardItems.value
                    _syncState.value = SyncState.Success
                }
                .onFailure {
                    _syncState.value = SyncState.Error(it.message ?: "同步失败")
                    if (it.message?.contains("401") == true) {
                        _loginState.value = LoginState.NotLoggedIn
                    }
                }
        }
    }

    fun copyToClipboard(content: String) {
        val clip = ClipData.newPlainText("剪贴板内容", content)
        clipboardManager.setPrimaryClip(clip)
    }

    private fun loadHistory() {
        viewModelScope.launch {
            api.getHistory()
                .onSuccess { jsonString ->
                    val items = parseHistoryJson(jsonString)
                    _clipboardItems.value = items
                }
                .onFailure {
                    if (it.message?.contains("401") == true) {
                        _loginState.value = LoginState.NotLoggedIn
                    } else {
                        _loginState.value = LoginState.Error("获取历史记录失败")
                    }
                }
        }
    }

    private fun parseHistoryJson(jsonString: String): List<ClipboardItem> {
        return try {
            val jsonArray = JSONArray(jsonString)
            List(jsonArray.length()) { index ->
                val item = jsonArray.getJSONObject(index)
                ClipboardItem(
                    id = item.getString("id"),
                    content = item.getString("content"),
                    deviceId = item.getString("device_id"),
                    timestamp = item.getLong("timestamp")
                )
            }
        } catch (e: Exception) {
            emptyList()
        }
    }
}

sealed class LoginState {
    object NotLoggedIn : LoginState()
    object Loading : LoginState()
    object LoggedIn : LoginState()
    data class Error(val message: String) : LoginState()
}

sealed class SyncState {
    object Idle : SyncState()
    object Syncing : SyncState()
    object Success : SyncState()
    data class Error(val message: String) : SyncState()
} 